// Decompiled on 周六 2月 22 19:31:49 CST 2025 with Zomboid Decompiler v0.1.3 using Vineflower.
package zombie.network.packets;

import java.nio.ByteBuffer;
import zombie.audio.BaseSoundEmitter;
import zombie.characters.BaseCharacterSoundEmitter;
import zombie.characters.IsoGameCharacter;
import zombie.core.network.ByteBufferWriter;
import zombie.core.raknet.UdpConnection;
import zombie.iso.IsoMovingObject;
import zombie.iso.IsoObject;
import zombie.iso.IsoWorld;
import zombie.network.packets.hit.MovingObject;

public class PlaySoundPacket implements INetworkPacket {
    String name;
    MovingObject object = new MovingObject();
    boolean loop;

    public void set(String _name, boolean _loop, IsoMovingObject source) {
        this.name = _name;
        this.loop = _loop;
        this.object.setMovingObject(source);
    }

    public void process() {
        IsoMovingObject isoMovingObject = this.object.getMovingObject();
        if (isoMovingObject instanceof IsoGameCharacter) {
            BaseCharacterSoundEmitter baseCharacterSoundEmitter = ((IsoGameCharacter)isoMovingObject).getEmitter();
            if (!this.loop) {
                baseCharacterSoundEmitter.playSoundImpl(this.name, (IsoObject)null);
            }
        } else if (isoMovingObject != null) {
            BaseSoundEmitter baseSoundEmitter = isoMovingObject.emitter;
            if (baseSoundEmitter == null) {
                baseSoundEmitter = IsoWorld.instance.getFreeEmitter(isoMovingObject.x, isoMovingObject.y, isoMovingObject.z);
                IsoWorld.instance.takeOwnershipOfEmitter(baseSoundEmitter);
                isoMovingObject.emitter = baseSoundEmitter;
            }

            if (!this.loop) {
                baseSoundEmitter.playSoundImpl(this.name, (IsoObject)null);
            } else {
                baseSoundEmitter.playSoundLoopedImpl(this.name);
            }

            baseSoundEmitter.tick();
        }
    }

    public String getName() {
        return this.name;
    }

    public IsoMovingObject getMovingObject() {
        return this.object.getMovingObject();
    }

    @Override
    public void parse(ByteBuffer b, UdpConnection connection) {
        this.object.parse(b, connection);
        this.name = zombie.GameWindow.ReadString(b);
        this.loop = b.get() == 1;
    }

    @Override
    public void write(ByteBufferWriter b) {
        this.object.write(b);
        b.putUTF(this.name);
        b.putByte((byte)(this.loop ? 1 : 0));
    }

    @Override
    public boolean isConsistent() {
        return this.name != null && !this.name.isEmpty();
    }

    @Override
    public int getPacketSizeBytes() {
        return 12 + this.name.length();
    }

    @Override
    public String getDescription() {
        return "\n\tPlaySoundPacket [name=" + this.name + " | object=" + this.object.getDescription() + " | loop=" + this.loop + " ]";
    }
}
